﻿/**
 * 类AutoResetEvent使用示例
 * author: zjh
 * create: 2019-08-02 14:10
 * 
 * */
using System;
using System.Threading;

namespace AutoResetEventClass
{
    internal class Program
    {
        private static AutoResetEvent autoReset;

        private static void Main(string[] args)
        {
            autoReset = new AutoResetEvent(false);

            Thread workerThread = new Thread(new ThreadStart(Worker));
            workerThread.IsBackground = true;
            workerThread.Start();

            string line = string.Empty;
            while (!(line = Console.ReadLine()).Equals("exit", StringComparison.OrdinalIgnoreCase))
            {
                if (line == "continue")
                {
                    // 继续线程
                    autoReset.Set();
                }
            }

            Console.WriteLine("Program end!");
            Console.ReadLine();
        }

        private static void Worker()
        {
            while (true)
            {
                Console.WriteLine("Thread {0} waiting...", Thread.CurrentThread.ManagedThreadId);

                // 线程等待
                autoReset.WaitOne();
                Console.WriteLine("Thread {0} continue.", Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(100);
            }
        }
    }
}